<?php
/**
 * PHPECS社交电商系统，使用thinkphp框架+MySQL数据库编写的小程序商城系统，基于LGPL协议开源授权
 * @package phpecs
 * @author qq(123865789)
 * @copyright 2018-2020 深圳塔灯网络科技有限公司
 * @version 2.0
 * @license http://www.phpecs.com/lgpl.html phpecs开源授权协议：GNU Lesser General Public License
 **/
namespace app\hgapi\controller;
use app\hgapi\model\activity\ActivityList;
use app\hgapi\model\activity\ActivityNum;
use app\hgapi\model\store\StoreProduct;
use app\hgapi\model\system\Message;
use app\hgapi\model\user\UserGrade;
use app\hgapi\model\user\UserLead;
use app\hgapi\model\goods\GoodsGiftCodeRecord;
use app\hgapi\model\goods\GoodsGift;
use app\hgapi\model\goods\GoodsPackage;
use app\hgapi\model\goods\GoodsGiftCode;
use app\hgapi\model\user\UserChoose;
use app\hgapi\model\user\UserLipin;
use app\hgapi\model\user\UserPackage;
use app\hgapi\model\user\User;
use app\hgapi\model\user\UserRole;
use app\hgapi\model\user\UserAddress;
use app\hgapi\model\user\UserCoupon;
use app\hgapi\model\user\UserTrade;
use app\hgapi\model\user\UserRecord;
use app\hgapi\model\user\UserCheck;
use app\hgapi\model\user\UserGold;
use app\hgapi\model\user\UserCash;
use app\hgapi\model\user\UserScene;
use app\hgapi\model\system\Site;
use app\hgapi\model\activity\ActivityClockQian;
use app\hgapi\model\store\StoreProductCoupon;
use app\hgapi\model\store\StoreOrder;
class UserApi extends Auth{

    /**
     * 获取用户信息
     */
    public function user_info(){
        $id = input('id');
        $user = User::getUserInfo(['id' => $id], 'balance, give, cashback, gold, grade');
        //查出权限
        $role = UserRole::getRole($id);
        //查出会员等级信息
        $grade = UserGrade::getGradeInfo(['grade' => $user['grade']]);
        $site = Site::getSite('open, retail_open, retail_type');
        $open = $site['open'];
        if ($site['retail_open'] == 1){
            if ($site['retail_type'] == 2 || $role['retail'] == 1){
                $retail = 1;
            }else{
                $retail = 0;
            }
        }else{
            $retail = 0;
        }
        $count = Message::countMessageZhi($id);
        successCode(compact('user', 'role', 'grade', 'open', 'retail', 'count'));
    }

    /**
     * 提交批发会员审核
     */
    public function pifa(){
        $id = input('id');
        $shouji = input('shouji');
        $find = db('pifa')->where(['uid' => $id, 'status' => 0])->find();
        if ($find){
            errorCode('请勿重复申请');
        }else{
            $data = [
                'uid' => $id,
                'phone' => $shouji,
                'status' => 0,
                'time' => time()
            ];
            $re = db('pifa')->insert($data);
            if ($re){
                successCode('申请成功,请等待审核通过');
            }else{
                errorCode('申请失败请稍后再试');
            }
        }
    }

    /**
     * 获取地址
     */
    public function get_address(){
        $id = input('id');
        $arr = UserAddress::getAddress($id, 'is_default asc,id desc');
        successCode($arr);
    }

    /**
     *添加地址
     */
    public function add_address(){
        $field = json_decode(input()['field'], true);
        $result = UserAddress::UpAddress($field, 0);
        if ($result){
            successCode('添加成功');
        }else{
            errorCode('添加失败');
        }
    }

    /**
     * 修改地址
     */
    public function edit_address(){
        $field = json_decode(input()['field'], true);
        $result = UserAddress::UpAddress($field, 1);
        if ($result){
            successCode('修改成功');
        }else{
            errorCode('修改失败');
        }
    }

    /**
     * 删除地址
     */
    public function del_address(){
        $id = input('id');
        $uid = input('uid');
        $result = UserAddress::DelAddress(['id' => $id, 'uid' => $uid]);
        if ($result){
            successCode('删除成功');
        }else{
            errorCode('删除失败');
        }
    }


    /**
     * 检测id和openid
     */
    public function jiance(){
        $id = input('id');
        $openid = input('openid');
        $result = User::getUserInfo(['id' => $id, 'openid' => $openid], '');
        if ($result['is_jin'] == 1){
            echo 2;
            exit;
        }
        if ($result){
            echo 1;
        }else{
            echo 0;
        }
    }

    /**
     * 签到记录
     */
    public function qianRecord(){
        $id = input('id');
        //查询数据
        $data = ActivityClockQian::getQian(['ch_id' => $id]);
        foreach ($data as $k => $v){
            $data[$k]['time'] = date('Y-m-d H:i:s', $v['time']);
        }
        successCode($data);
    }

    /**
     * 所有优惠券
     */
    public function whole_coupon(){
        $id = input('id'); //用户id
        $coupon = UserCoupon::selUserCoupon(['uid' => $id], 0);
        foreach ($coupon as $k => $v){
            //券的信息
            $coupon[$k]['coupon'] = StoreProductCoupon::getCoupon(['id' => $v['cid']], '');
        }
        successCode($coupon);
    }

    /**
     * 查询我的所有优惠券
     */
    public function my_coupon(){
        $id = input('id'); //用户id
        $type = input('type'); //查询是否可以用的 0可用的 1不可用
        $money = input('money'); //订单金额
        //可用券数组
        $available = [];
        //不可用券数组
        $disabled = [];
        $coupon = UserCoupon::selUserCoupon(['uid' => $id], 0);
        foreach ($coupon as $k => $v){
            //券的信息
            $quan = StoreProductCoupon::getCoupon(['id' => $v['cid']], '');
            $quan['id'] = $v['id']; //数组id替换为我领取的数据id
            $time = time(); //当前时间
            //判断有效时间
            if ($quan['term'] == '0'){ //0为指定开始结束时间
                $valid = explode(' - ', $quan['valid']);
                $start = strtotime($valid[0]);
                $end = strtotime($valid[1]);
                //判断当前优惠券是否在指定时间使用
                if ($time >= $start && $time <= $end && ($quan['doorsill'] == '0' ? true : $money >= $quan['full'] ? true : false)){
                    array_push($available, $quan);
                }else{
                    array_push($disabled, $quan);
                }
            }else{ //多少天内使用
                if (($v['time'] + $quan['valid'] * 24 * 60 * 60) > $time && ($quan['doorsill'] == '0' ? true : $money >= $quan['full'] ? true : false)){ //在指定时间内
                    array_push($available, $quan);
                }else{
                    array_push($disabled, $quan);
                }
            }
        }
        //折扣订单金额变化
        foreach ($available as $k => $v){
            if ($v['form'] == 1){
                $available[$k]['discount'] = round($money * $v['discount'] / 10, 1);
            }
        }
        foreach ($disabled as $k => $v){
            if ($v['form'] == 1){
                $disabled[$k]['discount'] = round($money * $v['discount'] / 10, 1);
            }
        }
        $data = $type == '0' ? $available : $disabled;
        successCode($data);
    }

    /**
     * 获取我的收钱码
     */
    public function collect_img(){
        $id = input('id'); //用户id
        $collect = User::getField(['id' => $id], 'collect', 0);
        if ($collect && file_exists($collect)){
            successCode($collect);
        }else{
            $access_token = access_token();
            $scene = "page:11,page_id:$id";
            $page = 'pages/loading/loading';
            $img = createImg($access_token, $scene, $page);
            $name = $id.'-'.time();
            //存储二维码路径
            $img_url = 'uploads/collect/code-'.$name.'.png';
            file_put_contents($img_url, $img);
            User::upField(['id' => $id], 'collect', $img_url);
            successCode($img_url);
        }
    }

    /**
     * 我的推广成员
     */
    public function member(){
        $uid = input('uid');
        $start = input('start');
        $limit = input('limit');
        $field = 'name, phone, time';
        $result = User::selMember(['upper' => $uid], $field, $start, $limit);
        foreach ($result as $k => $v){
            $result[$k]['time'] = date('Y-m-d', $v['time']);
            $result[$k]['name'] = base64_decode($v['name']);
        }
        successCode($result);
    }

    /**
     * 查询签到数据
     */
    public function get_activity(){
        $uid = input('id');
        $data = StoreOrder::getOrderQian($uid);
        successCode($data);
    }

    //签到详情
    public function get_activity2(){
        $uid = input('uid');
        $id = input('id');
        $todayYear = input('todayYear'); //本年
        $todayMonth = input('todayMonth'); //本月
        $showYear = input('showYear'); //日历当前年
        $showMonth = input('showMonth'); //日历当前月
        $todayss = input('todayss'); //今天多少号
        $qian = input('qian');
        $find = StoreOrder::getOrderQianXiang($uid, $id); //查询数据
        $address = UserTrade::getTrade(['uid' => $find['genus']]); //查出地址
        //判断签到信息 查询前一天的信息
        $qtime = time() - 3600 * 24;
        $qtian = ActivityClockQian::getFindQian(['ch_id' => $find['id'], 'Year' => date('Y', $qtime), 'Month' => date('m', $qtime), 'Date' => date('d', $qtime), 'use' => $find['use']]);
        $dangshi = getdate($find['h_time']);
        $dangqian = getdate(strtotime($todayYear.'-'.$todayMonth.'-'.$todayss));
        //判断是否第一天签到
        if (($dangshi['year'] === $dangqian['year']) && ($dangshi['yday'] === $dangqian['yday'])){
            $is = 4;
        }elseif (($dangshi['year'] === $dangqian['year']) && ($dangshi['yday'] === $dangqian['yday'] - 1)){
            $is = 2;
        }else{
            if ($find['rule'] == 3){ //判断是否一天签到两次 查询前一天是否签到了两次(一次)
                if ($qtian['zao'] == 1 && $qtian['wan'] == 1){
                    $is = 2;
                }else{
                    //查询最后一天时间的时间
                    $h_time = ActivityClockQian::getField(['ch_id' => $find['id'], 'use' => $find['use']], 'time');
                    $h_time = $h_time ? $h_time : $find['h_time'];
                    if (time() - $h_time < 3600 * 24 * 3 && $find['status'] != 1 && !$find['hexiao']){
                        $is = 1;
                    }else{
                        $is = 0;
                    }
                }
            }elseif ($find['rule'] == 2){
                if ($qtian['wan'] == 1){
                    $is = 2;
                }else{
                    //查询最后一天时间的时间
                    $h_time = ActivityClockQian::getField(['ch_id' => $find['id'], 'use' => $find['use']], 'time');
                    $h_time = $h_time ? $h_time : $find['h_time'];
                    if (time() - $h_time < 3600 * 24 * 3 && $find['status'] != 1 && !$find['hexiao']){
                        $is = 1;
                    }else{
                        $is = 0;
                    }
                }
            }else{
                if ($qtian['zao'] == 1){
                    $is = 2;
                }else{
                    //查询最后一天时间的时间
                    $h_time = ActivityClockQian::getField(['ch_id' => $find['id'], 'use' => $find['use']], 'time');
                    $h_time = $h_time ? $h_time : $find['h_time'];
                    if (time() - $h_time < 3600 * 24 * 3 && $find['status'] != 1 && !$find['hexiao']){
                        $is = 1;
                    }else{
                        $is = 0;
                    }
                }
            }
        }
        $data1 = [
            'ch_id' => $find['id'],
            'Year' => $todayYear,
            'Month' => $todayMonth,
            'Date' => $todayss,
            'use' => $find['use'],
        ];
        //签到
        if ($qian == 1){ //是否签到
            $h = date('H', time());
            if (7 <= $h && $h < 8){
                $data2['zao'] = 1;
            }elseif (20 <= $h && $h < 21){
                $data2['wan'] = 1;
            }
            $cun = ActivityClockQian::getFindQian($data1);
            if ($cun){
                ActivityClockQian::upQian($data1, $data2);
            }else{
                $data = array_merge($data1, $data2);
                $data['time'] = time();
                ActivityClockQian::addQian($data);
            }
        }
        //查询本月的所有签到情况
        $Date = ActivityClockQian::getColumn(['ch_id' => $find['id'], 'Year' => $todayYear, 'Month' => $todayMonth, 'use' => $find['use']], 'Date');
        //查询日历当前月的所有签到情况
        $Date2 = ActivityClockQian::getColumn(['ch_id' => $find['id'], 'Year' => $showYear, 'Month' => $showMonth, 'use' => $find['use']], 'Date');
        //共签到多少条
        if ($find['rule'] == 3){
            $where['zao'] = 1;
            $where['wan'] = 1;
        }elseif ($find['rule'] == 2){
            $where['wan'] = 1;
        }else{
            $where['zao'] = 1;
        }
        $where['ch_id'] = $find['id'];
        $where['use'] = $find['use'];
        $count = ActivityClockQian::countQian($where);
        if ($count == $find['tian'] && $count > 0){ //完成任务
            if ($qian == 1){
                if ($find['status'] == 6){
                    $ord['status'] = 1;
                }
                $ord['active_status'] = 1;
                StoreOrder::upOrder(['id' => $id], $ord);
                if ($find['tui']){
                    //增加返现
                    User::incField($uid, 'cashback', $find['price']);
                }
                $formId = input('formId');
            }
            $is = 3;
        }
        //生成转发二维码和信息
        $imgs = "uploads/clock/$uid-$id.png";
        if (!file_exists($imgs)){
            $access_token = access_token();
            $scene = "page:7,upper:$uid,page_id:$find[clock_id]";
            $img = createImg($access_token, $scene);
            file_put_contents("uploads/clock/$uid-$id.png", $img);
        }
        $field = 'name, portrait, card';
        $user = User::getUserInfo(['id' => $uid], $field);
        $user['name'] = base64_decode($user['name']);

        //活动时间
        $start = $find['h_time'] + 3600 * 24;
        $end = $start + 3600 * 24 * ($find['tian'] - 1);
        $shijian = date('Y年m月d号', $start) . ' - ' . date('Y年m月d号', $end);
        $cun = ActivityClockQian::getFindQian($data1);
        successCode(['data' => $find, 'Date' => $Date, 'Date2' => $Date2, 'count' => $count, 'is' => $is, 'qr_code' => $imgs, 'user' => $user, 'cun' => $cun, 'shijian' => $shijian, 'formId' => $formId, 'address' => $address]);
    }

    /**
     * 重新签到
     */
    public function chongqian(){
        $id = input('id'); //订单id
        $uid = input('uid'); //用户id
        //查询是否已经过期或者时间已到
        $field = 'h_time, use';
        $order = StoreOrder::getOrder(['id' => $id], $field);
        if (time() - $order['h_time'] > 3600 * 72){
            errorCode('时间已过期');
        }elseif ($order['use'] == 1){
            errorCode('该活动已经使用过一次重签机会');
        }
        $card = User::getField(['id' => $uid], 'card', 0);
        if ($card < 1){
            errorCode('您的重签卡不够');
        }
        $is = StoreOrder::upOrder(['id' => $id], ['h_time' => time(), 'use' => 1]);
        if ($is){
            User::decField($uid, 'card');
            successCode('操作成功');
        }else{
            errorCode('操作失败');
        }
    }

    /**
     * 直接发货
     */
    public function fahuo(){
        $id = input('id'); //订单id
        $uid = input('uid'); //用户id
        $ord = [
            'status' => 1,
            'active_status' => 2
        ];
        $is = StoreOrder::upOrder(['id' => $id, 'uid' => $uid], $ord);
        if ($is){
            successCode('操作成功');
        }else{
            errorCode('操作失败');
        }
    }

    /**
     * 核销码
     */
    public function hexiao_img2(){
        $id = input('id'); //订单id
        $uid = input('uid'); //用户id
        //生成转发二维码和信息
        $genus = StoreOrder::getOrderGenus($id, $uid);
        $imgs = "uploads/clock_in/$uid-$id.png";
        if (!file_exists($imgs)){
            $access_token = access_token();
            $scene = "page:10,uid:$uid,page_id:$id,yid:$genus";
            $img = createImg($access_token, $scene);
            file_put_contents("uploads/clock_in/$uid-$id.png", $img);
        }
        $ord = [
            'hexiao' => $imgs,
            'active_status' => 2
        ];
        $is = StoreOrder::upOrder(['id' => $id, 'uid' => $uid], $ord);
        if ($is){
            successCode('操作成功');
        }else{
            errorCode('操作失败');
        }
    }

    /**
     * 查询余额
     */
    public function yue(){
        $id = input('id'); //用户id
        $start = input('start'); //用户id
        $limit = input('limit'); //用户id
        $type = input('type'); //获取类型
        $field = 'balance, give, cashback';
        $data = User::getUserInfo(['id' => $id], $field); //查出余额
        //查出充值记录
        if ($type == 0){
            //查出充值记录
            $record = UserRecord::selRecord(['uid' => $id, 'status' => 1], $start, $limit);
        }elseif ($type == 1){
            $record = UserCheck::selCheck(['uid' => $id, 'status' => 1], $start, $limit);
        }else{
            $record = StoreOrder::selOrder(['uid' => $id, 'status' => ['not in', [0, 5]]], '', $start, $limit);
        }
        foreach ($record as $k => $v){
            $record[$k]['time'] = date('Y-m-d H:i:s', $v['time']);
        }
        successCode(['data' => $data, 'record' => $record]);
    }

    /**
     * 查询记录
     */
    public function jilu(){
        $type = input('type'); //获取类型
        $id = input('id'); //用户id
        $start = input('start'); //用户id
        $limit = input('limit'); //用户id
        if ($type == 0){
            //查出充值记录
            $record = UserRecord::selRecord(['uid' => $id, 'status' => 1], $start, $limit);
        }elseif ($type == 1){
            $record = UserCheck::selCheck(['uid' => $id, 'status' => 1], $start, $limit);
        }else{
            $record = StoreOrder::selOrder(['uid' => $id, 'status' => ['not in', [0, 5]]], '', $start, $limit);
        }
        foreach ($record as $k => $v){
            $record[$k]['time'] = date('Y-m-d H:i:s', $v['time']);
        }
        successCode($record);
    }

    /**
     * 查询佣金
     */
    public function gold(){
        $id = input('id'); //用户id
        //先查出佣金余额
        $gold = User::getField(['id' => $id], 'gold', 0);
        //查出佣金记录
        $record = UserGold::getGoldTiao($id, 5);
        foreach ($record as $k => $v){
            $record[$k]['time'] = date('Y-m-d H:i:s', $v['time']);
        }
        successCode(['gold' => $gold, 'record' => $record]);
    }

    /**
     * 申请提现
     */
    public function cash(){
        $id = input('id'); //提现用户
        $cash = input('cash'); //提现金额
        //查询可提现金额
        $gold = User::getField(['id' => $id], 'gold', 0);
        if ($gold < $cash){
            errorCode('提现金额大于可用佣金');
        }
        //判断是否有无正在审核的数据
        $cun = UserCash::getCash(['uid' => $id, 'status' => 0]);
        if ($cun){
            errorCode('请等待上笔订单审核通过');
        }
        $time = date('YmdHis');
        $ord_id = "$time$id"; //订单号
        $data = [
            'order' => $ord_id,
            'money' => $cash,
            'uid' => $id,
            'time' => time(),
            'status' => 0
        ];
        $re = UserCash::add($data);
        if ($re){
            successCode('提交申请成功,请等待审核');
        }else{
            errorCode('提交申请失败,情稍后重试');
        }
    }

    /**
     * 查看大礼包下面的礼品
     */
    public function cha_lipin(){
        $id = input('id'); //大礼包id
        $uid = input('uid'); //用户id
        //查询我的所有大礼包
        $package = UserPackage::getField(['uid' => $uid], 'package');
        $package = explode(',', $package);
        if (in_array($id, $package)){
            $is = 1;
        }else{
            $is = 0;
        }
        //查询大礼包下面的礼品
        $gid = GoodsPackage::getField(['id' => $id], 'gid');
        $gids = explode(',', $gid);
        $list = GoodsGift::selGift(['id' => ['in', $gids]]);
        foreach ($list as $k => $v){
            $list[$k]['index'] = numToWord($k+1);
        }
        successCode(['list' => $list, 'info' => $is]);
    }

    /**
     * 获取我的招商二维码呢
     */
    public function recruit_img(){
        $id = input('id'); //用户id
        $type = input('type'); //获取的二维码类型 0提供礼品商家码 1引流商家码
        $field = 'carry, lead';
        $find = User::getUserInfo(['id' => $id], $field);
        if ($type == 0){
            if ($find['carry'] && file_exists($find['carry'])){
                successCode($find['carry']);
            }else{
                $access_token = access_token();
                $scene = "page:3,page_id:$id";
                $img = createImg($access_token, $scene);
                $name = $id.'-'.time();
                file_put_contents('uploads/carry/code-'.$name.'.png', $img);
                //存储二维码路径
                $img_url = 'uploads/carry/code-'.$name.'.png';
                User::upField(['id' => $id], 'carry', $img_url);
                successCode($img_url);
            }
        }else{
            if ($find['lead'] && file_exists($find['lead'])){
                successCode($find['lead']);
            }else{
                $access_token = access_token();
                $scene = "page:4,page_id:$id";
                $img = createImg($access_token, $scene);
                $name = $id.'-'.time();
                file_put_contents('uploads/lead/code-'.$name.'.png', $img);
                //存储二维码路径
                $img_url = 'uploads/lead/code-'.$name.'.png';
                User::upField(['id' => $id], 'lead', $img_url);
                successCode($img_url);
            }
        }
    }

    /**
     * 查出当前核销码未被领取的 按期数分组
     */
    public function he_xiao(){
        $id = input('id'); //礼品id
        $uid = input('uid'); //用户id
        $count = GoodsGiftCode::whereCode($id); //共有多少期
        $list = GoodsGiftCode::selCodeZhi($id);
        //把所有已查出来的期数添加进数组
        $stages = [];
        foreach ($list as $k => $v){
            array_push($stages, $v['stage']);
        }
        //循环总数添加没查出来的
        $data = [];
        for ($i=0;$i<$count;$i++){
            $qi = $i+1;
            if (!in_array($qi, $stages)){
                $arr = [
                    'lid' => $id,
                    'stage' => $qi,
                    'status' => 2
                ];
                array_push($data, $arr);
            }else{
                foreach ($list as $k => $v){
                    if ($v['stage'] == $qi){
                        array_push($data, $list[$k]);
                    }
                }
            }

        }
        //查询出用户已领取的当前礼品记录
        $field = 'stage, img, time';
        $jilu = UserLipin::selLipin(['uid' => $uid, 'lid' => $id], $field);
        foreach ($data as $k => $v){
            $data[$k]['newsstage'] = numToWord($v['stage']);
            foreach ($jilu as $key => $val){
                if ($v['stage'] == $val['stage']){
                    if ($v['status'] == 0){
                        $find = GoodsGiftCodeRecord::getRe(['uid' => $uid, 'lid' => $id, 'stage' => $val['stage']]);
                        if ($find){
                            $data[$k]['status'] = 3;
                            $data[$k]['time'] = date('Y-m-d H:i:s', $find['h_time']);
                        }else{
                            if (($val['time'] + 2592000) < time()){
                                $data[$k]['status'] = 2;
                            }else{
                                $data[$k]['status'] = 1;
                            }
                            $data[$k]['time'] = date('Y-m-d H:i:s', $val['time']);
                        }
                        $data[$k]['img'] = $val['img'];
                    }
                }
            }
        }
        //商家地址
        $address = GoodsGift::getGift(['id' => $id]);
        //查出用户是否已经获取到手机号
        $phone = User::getField(['id' => $uid], 'phone', 0);
        successCode(['list' => $data, 'address' => $address, 'phone' => $phone]);
    }

    /**
     * 领取核销码
     */
    public function hexiao_img(){
        $id = input('id'); //用户id
        $lid = input('lid'); //礼品id
        $stage = input('stage'); //期数
        $yid = input('yid'); //所属引流商家
        //如果是多期的话 第2期开始要判断它上期是否领取
        if ($stage >= 2){
            //查询上期是否领取
            $shang = UserLipin::getLipin(['uid' => $id, 'lid' => $lid, 'stage' => $stage - 1]);
            if (!$shang){
                errorCode('请先领取上一期');
            }
        }
        //一个月内只能领取一期
        $time = UserLipin::getField(['uid' => $id, 'lid' => $lid, 'time' => ['lt', time()]], 'time');
        //查出礼品
        $find = GoodsGift::getGift(['id' => $lid]);
        if (($time + ($find['ge'] ? $find['ge'] * 24 * 60 * 60 : 259200)) > time() && $find['mode'] != 1){
            errorCode($find['ge'] ? $find['ge'] . '天内只能领取一期' : '30天内只能领取一期');
        }
        //添加数据库存入scene值
        $arr = [
            'uid' => $id,
            'lid' => $lid,
            'stage' => $stage,
            'yid' => $yid,
        ];
        $page_id = UserScene::add($arr);
        $access_token = access_token();
        $scene = "page:5,page_id:$page_id";
        $img = createImg($access_token, $scene);
        $name = $id.'-'.time();
        file_put_contents('uploads/hexiao/code-'.$name.'.png', $img);
        //存储二维码路径
        $img_url = 'uploads/hexiao/code-'.$name.'.png';
        $data = [
            'uid' => $id,
            'lid' => $lid,
            'img' => $img_url,
            'stage' => $stage,
            'time' => time()
        ];
        UserLipin::add($data);
        successCode($img_url);
    }

    /**
     * 买单折扣
     */
    public function check_info(){
        $uid = input('uid'); //用户id
        $give = Site::getField('give');; //折扣信息
        $field = 'balance, give';
        $money = User::getUserInfo(['id' => $uid], $field);
        successCode(['give' => $give, 'money' => $money]);
    }

    /**
     * 获取我的推广二维码
     */
    public function spread_img(){
        $id = input('id'); //用户id
        $site = Site::getSite('tui1, tui2, tui3, color');
        $qr_code = User::getField(['id' => $id], 'qr_code', 0);
        if (!$qr_code || !file_exists($qr_code)){
            $access_token = access_token();
            $scene = "page:2,upper:$id";
            $img = createImg($access_token, $scene);
            $name = $id.'-'.time();
            file_put_contents('uploads/qrcode/code-'.$name.'.png', $img);
            //存储二维码路径
            $qr_code = 'uploads/qrcode/code-'.$name.'.png';
            User::upField(['id' => $id], 'qr_code', $qr_code);
        }
        $field = 'name, portrait';
        $user = User::getUserInfo(['id' => $id], $field);
        $user['name'] = base64_decode($user['name']);
        successCode(['site' => $site, 'user' => $user, 'qr_code' => $qr_code]);
    }

    /**
     * 用户查看我的大礼包
     */
    public function myPackage(){
        $id = input('id'); //用户id
        //查找出所有已拥有大礼包
        $list = UserPackage::getPackageY($id);
        foreach ($list as $k => $v){
            $list[$k]['time'] = date('Y-m-d', $v['start']) . '-' . date('Y-m-d', $v['end']);
        }
        successCode($list);
    }

    /**
     * 查出合作商家
     */
    public function hezuo(){
        $id = input('id'); //礼包id
        $list = UserChoose::selYin($id);
        $imgUrl = 'uploads/hezuo/package-'.$id.'.png';
        if (!file_exists($imgUrl)){
            $access_token = access_token();
            $scene = "page:12,page_id:$id";
            $img = createImg($access_token, $scene);
            file_put_contents($imgUrl, $img);
        }
        successCode(['data' => $list, 'img' => $imgUrl]);
    }

    /**
     * 引流审核
     */
    public function yin_shenhe(){
        $id = input('id');
        $type = input('type');
        $find = UserChoose::getUserChooseInfo(['id' => $id], 'uid, package');
        if ($type == 1){
            $data = [
                'img' => $this->package_img($find['package'], $find['uid']),
                'status' => 1
            ];
            $re = UserChoose::edit(['id' => $id], $data);
            if ($re){
                //是否同时提交审核引流商家
                $lead = UserLead::getLead(['uid' => $find['uid']], '');
                if ($lead){
                    //添加商家信息
                    $data2 = [
                        'uid' => $find['uid'],
                        'name' => $lead['name']
                    ];
                    $trade = UserTrade::getTrade(['uid' => $find['uid']]);
                    if ($trade){
                        $re2 = UserTrade::edit(['id' => $find['uid']], $data2);
                    }else{
                        $re2 = UserTrade::add($data2);
                    }
                    //成功后申请数据的状态
                    if ($re2){
                        //因为申请手机时就已经修改手机所以不必重复修改了
                        //修改成为引流商家
                        UserRole::upField(['uid' => $find['uid']], 'drainage', 1);
                        //修改当前审核状态
                        UserLead::upField(['uid' => $find['uid']], 'status', 1);
                    }
                }
                successCode('通过成功');
            }else{
                errorCode('通过失败');
            }
        }else{
            $re = UserChoose::upField(['id' => $id], 'status', 2);
            if ($re){
                UserLead::upField(['uid' => $find['uid']], 'status', 2);
                successCode('拒绝成功');
            }else{
                errorCode('拒绝失败');
            }
        }
    }

    /**
     * 获取我的大礼包二维码
     * @param $id
     * @param $uid
     * @return string
     */
    public function package_img($id, $uid){
        $access_token = access_token();
        $scene = "page:9,page_id:$id,yid:$uid";
        $img = createImg($access_token, $scene);
        $name = $id.'-'.time().'-'.$uid;
        file_put_contents('uploads/package/code-'.$name.'.png', $img);
        //存储二维码路径
        $img_url = 'uploads/package/code-'.$name.'.png';
        return $img_url;
    }

    /**
     * 图片上传
     */
    public function upload(){
        upload('lipin');
    }

    /**
     * 活动数据
     */
    public function activity_list(){
        $list = ActivityList::selActivityList(['status' => 1], '');
        successCode($list);
    }

    /**
     * 查询一条数据
     */
    public function activity_details(){
        $id = input('id');
        $uid = input('uid');
        $find = ActivityList::getActivityListInfo(['id' => $id]);
        $find['list'] = ActivityNum::selActivityNum(['uid' => $uid, 'aid' => $id], 'name, time');
        successCode($find);
    }

    /**
     * 抽奖
     */
    public function activity_chou(){
        $id = input('id');
        $uid = input('uid');
        $find = ActivityList::getActivityListInfo(['id' => $id], 'action, pid, integral, draw, num');
        //查出用户抽奖记录
        $count = ActivityNum::countActivityNum(['uid' => $uid, 'aid' => $id]);
        if ($count >= $find['num']) errorCode('最多可参与' . $find['num'] . '次'); //抽奖上限
        switch ($find['action']){
            case 1:
                break;
            case 2: //积分抽奖
                //查出用户积分
                $integral = User::getField(['id' => $uid], 'integral');
                if ($integral < $find['integral']) {
                    errorCode('积分不足');
                }else{
                    User::decField($uid, 'integral', $find['integral']);
                }
        }
        $draw = json_decode($find['draw'], true);
        $proArr = [];
        foreach ($draw as $k => $v){
            array_push($proArr, $v['chance']);
        }
        $result = '';
        //概率数组的总概率精度
        $proSum = array_sum($proArr); //计算数组中元素的和
        //概率数组循环
        foreach ($proArr as $key => $proCur) {
            $randNum = mt_rand(1, $proSum);
            if ($randNum <= $proCur) { //如果这个随机数小于等于数组中的一个元素，则返回数组的下标
                $result = $key;
                break;
            } else {
                $proSum -= $proCur;
            }
        }
        unset ($proArr);
        //添加中奖结果
        $data = [
            'uid' => $uid,
            'aid' => $id,
            'name' => $draw[$result]['name'],
            'result' => $result,
            'time' => time(),
        ];
        ActivityNum::add($data);
        //发送奖品
        sendGift($draw[$result]['song'], $draw[$result]['zhi'], $uid);
        successCode($result);
    }

    /**
     * 查出活动商品
     */
    public function activity_shop(){
        $id = input('id');
        $pid = ActivityList::getField(['id' => $id], 'pid');
        $pid = explode(',', $pid);
        $list = StoreProduct::selProduct(['id' => ['in', $pid]], '', '');
        successCode($list);
    }
}





